
package com.seekting.gongzhu.clientsdk;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import com.seekting.gongzhu.sdk.Info;
import com.seekting.gongzhu.sdk.KLog;

public class Client implements Connector {

    private Socket socket;

    public Thread connectThread;
    private DataOutputStream out;
    private DataInputStream in;
    private ClientNetWorkHelper clientNetWorkHelper;
    private Player player;

    public void connect(String ip) {
        connectThread = new Thread(new Runnable() {

            @Override
            public void run() {

                String ip = null;
                int port = Info.UDP_LOCAL_PORT;
                // 与服务端建立连接
                try {
                    socket = new Socket(ip, Info.HOST_PORT);
                    socket.setKeepAlive(true);
                    KLog.d("客户端已经建立连接");
                    out = new DataOutputStream(socket.getOutputStream());
                    in = new DataInputStream(socket.getInputStream());
                    clientNetWorkHelper=new ClientNetWorkHelper(socket, out, in, 0,Client.this, Client.this);
                    clientNetWorkHelper.startRecMsg(Client.this);
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                    KLog.d("UnknownHostException" + e.getMessage());
                } catch (IOException e) {
                    e.printStackTrace();
                    KLog.d("IOException" + e.getMessage());
                }
            }
        });
        connectThread.start();
    }

    @Override
    public void send(String ip, String str) {
        clientNetWorkHelper.send(str);
    }

    @Override
    public void onReceive(String ip, String str) {

        System.out.println("收消息:" + str);
        if (player != null) {
            player.onReceive(ip, str);
        }
    }

    @Override
    public ConnectResult onConnect(String ipPort) {
        return null;
    }

    @Override
    public void onDisConnect(int index, String ipPort) {
        KLog.e("断开连接");
    }

    public void bind(Player player) {
        this.player = player;
        player.setConnector(this);
    }

    @Override
    public void findHost() {
        ServiceFinder serviceFinder = new ExecetorServiceFinder();
        serviceFinder.find(player);
    }

    @Override
    public void join(String ip) {
        connect(ip);
    }

    @Override
    public boolean leave() {
        return false;
    }

}
